package com.qixia.upload.util;

import com.creek.data.DataMap;
import com.github.pagehelper.PageInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 返回数据
 */
public class R extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;

	public R() {
		put("code", 0);
	}
	public static R error() {
		return error(500, "未知异常，请联系管理员");
	}

	public static R error(String message) {
		return error(500, message);
	}

	public static R error(int code, String message) {
		R r = new R();
		r.put("code", code);
		r.put("msg", message);
		return r;
	}

	public static R ok(String message) {
		R r = new R();
		r.put("msg", message);
		return r;
	}

	public static R ok(Map<String, Object> map) {
		R r = new R();
		r.putAll(map);
		return r;
	}

	public static R ok() {
		return new R();
	}

	@Override
	public R put(String key, Object value) {
		super.put(key, value);
		return this;
	}

	public static R pageFormat(Integer page, Integer pageSize, List<?> dataList) {
		if (page == null) {
			page = 1;
		}
		if (pageSize == null) {
			pageSize = 20;
		}
		long total = new PageInfo<>(dataList).getTotal();
		return setUpMap(dataList, page, pageSize, total);
	}

	private static R setUpMap(List<?> dataList, int page, int pageSize, long total) {
		DataMap dataMap = new DataMap();
		if (dataList != null) {
			dataMap.put("data", dataList);
		} else {
			dataMap.put("data", new ArrayList<>());
		}
		boolean hasNext = total - (long) page * pageSize > 0;
		dataMap.put("total", total);
		dataMap.put("hasNext", hasNext);
		dataMap.put("page", page);
		return R.ok(dataMap);
	}

}

